package com.zsr.example.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsr.example.config.annotation.RequiresPermissions;
import com.zsr.example.entity.EduPath;
import com.zsr.example.entity.EduPathStep;
import com.zsr.example.service.EduPathService;
import com.zsr.example.service.EduPathStepService;
import com.zsr.example.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 学习路径步骤 前端控制器
 * </p>
 *
 * @author zsr
 * @since 2022-02-10
 */
@RestController
@RequestMapping("/step")
public class EduPathStepController {

    @Autowired
    private EduPathService pathService;

    @Autowired
    private EduPathStepService stepService;

    /**
     * example query the learning path list
     */
    @RequiresPermissions("path:list")
    @PostMapping("/pageListStepCondition/{current}/{limit}")
    public JSONObject listArticle(@PathVariable long current,
                                  @PathVariable long limit) {
        Page<EduPathStep> page = new Page<>(current, limit);
        QueryWrapper<EduPathStep> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        stepService.page(page, queryWrapper);
        return CommonUtil.successPage(page.getTotal(), page.getRecords());
    }

    @RequiresPermissions("path:list")
    @GetMapping("/getStep/{id}")
    public JSONObject listArticle(@PathVariable String id) {
        EduPathStep step = stepService.getById(id);
        return CommonUtil.successJson(step);
    }

    @RequiresPermissions("path:update")
    @PostMapping("/saveOrUpdateStep")
    public JSONObject saveOrUpdateStep(@RequestBody EduPathStep step) {
        if (StringUtils.isEmpty(step.getId())) {
            EduPath path = pathService.getById(step.getPathId());
            path.setStepsCount(path.getStepsCount() + 1);
            pathService.update(path, null);
        }
        stepService.saveOrUpdate(step);
        return CommonUtil.successJson();
    }
}

